package com.kg.elysia.db;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.mysqlclient.MySQLBatchException;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.Tuple;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author zj
 * @since 2025/10/20 14:46
 */
public class DatabaseVerticle extends AbstractVerticle {

    private static final String DATABASE_Host = "localhost";

    private static final int DATABASE_PORT = 3306;

    private static final String DATABASE_USER = "root";

    private static final String DATABASE_PASSWORD = "root";

    private static final String DATABASE_NAME = "mural_db";

    private MySQLPool client;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        MySQLConnectOptions connectOptions = new MySQLConnectOptions()
                .setPort(DATABASE_PORT)
                .setHost(DATABASE_Host)
                .setDatabase(DATABASE_NAME)
                .setUser(DATABASE_USER)
                .setPassword(DATABASE_PASSWORD);
        PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
        client = MySQLPool.pool(vertx, connectOptions, poolOptions);
        client.query("SELECT 1").execute(ar -> {
            if (ar.succeeded()) {
                startPromise.complete();
            } else {
                startPromise.fail(ar.cause());
            }
        });
    }

    // 查询所有壁画
    public void getAllMurals(Promise<JsonArray> promise) {
        client.query("SELECT * FROM mural")
                .execute(ar -> {
                    if (ar.succeeded()) {
                        JsonArray result = new JsonArray();
                        for (Row row : ar.result()) {
                            result.add(row.toJson());
                        }
                        promise.complete(result);
                    } else {
                        promise.fail(ar.cause());
                    }
                });
    }

    // 添加壁画
    public void addMural(Mural mural, Promise<Void> promise) {
        String sql = "INSERT INTO mural (" +
                "tomb_name, mural_position, reference, gender, identity, scene, " +
                "upper_garment, lower_garment, accessory, shoes, color, pattern, " +
                "period, dynasty, institution, culture, social_class, religion" +
                ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        Tuple params = Tuple.of(
                mural.getTombName(),
                mural.getMuralPosition(),
                mural.getReference(),
                mural.getGender(),
                mural.getIdentity(),
                mural.getScene(),
                mural.getUpperGarment(),
                mural.getLowerGarment(),
                mural.getAccessory(),
                mural.getShoes(),
                mural.getColor(),
                mural.getPattern(),
                mural.getPeriod(),
                mural.getDynasty(),
                mural.getInstitution(),
                mural.getCulture(),
                mural.getSocialClass(),
                mural.getReligion()
        );

        client.preparedQuery(sql)
                .execute(params)
                .onSuccess(res -> promise.complete())
                .onFailure(promise::fail);
    }

    // 批量新增壁画数据
    public void batchAddMurals(List<Mural> murals, Promise<Integer> promise) {
        if (murals == null || murals.isEmpty()) {
            promise.complete(0);
            return;
        }

        String sql = "INSERT INTO mural (" +
                "tomb_name, mural_position, reference, gender, identity, scene, " +
                "upper_garment, lower_garment, accessory, shoes, color, pattern, " +
                "period, dynasty, institution, culture, social_class, religion" +
                ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        try {
            // 将壁画列表转换为Tuple列表
            List<Tuple> batchParams = murals.stream()
                    .map(mural -> Tuple.of(
                            mural.getTombName(),
                            mural.getMuralPosition(),
                            mural.getReference(),
                            mural.getGender(),
                            mural.getIdentity(),
                            mural.getScene(),
                            mural.getUpperGarment(),
                            mural.getLowerGarment(),
                            mural.getAccessory(),
                            mural.getShoes(),
                            mural.getColor(),
                            mural.getPattern(),
                            mural.getPeriod(),
                            mural.getDynasty(),
                            mural.getInstitution(),
                            mural.getCulture(),
                            mural.getSocialClass(),
                            mural.getReligion()
                    ))
                    .collect(Collectors.toList());

            // 执行批量插入
            client.preparedQuery(sql)
                    .executeBatch(batchParams)
                    .onSuccess(res -> {
                        // 返回插入的记录数
                        int affectedRows = res.rowCount();
                        promise.complete(affectedRows);
                    })
                    .onFailure(promise::fail);
        } catch (MySQLBatchException e) {
            e.printStackTrace();
            System.err.println("Error message: " + e.getMessage());
        }
    }

    public void truncateTable(Promise<Void> promise) {
        client.query("TRUNCATE TABLE mural")
                .execute(ar -> {
                    if (ar.succeeded()) {
                        promise.complete();
                    } else {
                        promise.fail(ar.cause());
                    }
                });
    }
}
